﻿<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title>License Key Details</title>
    <style type="text/css">
        body {
            background-color: rgb(233, 237, 241);
            font-family: 'Segoe UI',Arial;
        }

        table {
            margin: 5px;
            width: 100%;
        }

        .label {
            width: 343px;
        }
    </style>

    <script src="../../ClientGlobalContext.js.aspx" type="text/javascript"></script>
    <script src="../Scripts/jquery_1.7.1.min.js" type="text/javascript"></script>
    <script src="../Scripts/json2.js" type="text/javascript"></script>
    <script src="../Scripts/crmlicensing.lib.min.js" type="text/javascript"></script>
    <script type="text/javascript">

        //NOTE: Change this to your solution Prefix;
        this.LicensePrefix = "clbk_/";

        //Obtains the server url
        function GetServerUrl() {
            var serverUrl = GetGlobalContext().getServerUrl();

            // Adjust URL for differences between on premise and online 
            if (serverUrl.match(/\/$/)) {
                serverUrl = serverUrl.substring(0, serverUrl.length - 1);
            }
            return serverUrl;
        }

        //Publishes the web resource for the license
        function PublishLicense() {
            Message.value = "Publishing License...";

            var parameterxml = "&lt;importexportxml&gt;&lt;webresources&gt;&lt;webresource&gt;" + LicenseKeyId.value + "&lt;/webresource&gt;&lt;/webresources&gt;&lt;/importexportxml&gt;";
            var request = ""
            request += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
            request += "  <s:Body>";
            request += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
            request += "      <request i:type=\"b:PublishXmlRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
            request += "        <a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
            request += "          <a:KeyValuePairOfstringanyType>";
            request += "            <c:key>ParameterXml</c:key>";
            request += "            <c:value i:type=\"d:string\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">" + parameterxml + "</c:value>";
            request += "          </a:KeyValuePairOfstringanyType>";
            request += "        </a:Parameters>";
            request += "        <a:RequestId i:nil=\"true\" />";
            request += "        <a:RequestName>PublishXml</a:RequestName>";
            request += "      </request>";
            request += "    </Execute>";
            request += "  </s:Body>";
            request += "</s:Envelope>";

            $.ajax({
                type: "POST",
                contentType: "text/xml; charset=utf-8",
                url: GetServerUrl() + "/XRMServices/2011/Organization.svc/web",
                data: request,
                beforeSend: function (XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("Accept", "application/xml");
                    XMLHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
                },
                success: function (data, textStatus, XmlHttpRequest) {
                    Message.value = "License Published.";
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(errorThrown);
                }

            });


        }

        //Creates or Updates the web resource containing the license
        function SaveLicense() {
            Message.value = "Saving License...";

            var serverUrl = GetServerUrl();
            var webResource = {};

            //Determine if it is an UPDATE or CREATE and set the options accordingly
            var ODataURL = serverUrl + "/XRMServices/2011/OrganizationData.svc/WebResourceSet";
            if (LicenseKeyId.value) {
                ODataURL += "(guid'" + LicenseKeyId.value + "')";
            }
            else {
                webResource.DisplayName = "License File";
                webResource.Name = LicensePrefix + GetGlobalContext().getOrgUniqueName() + ".lic";
                webResource.WebResourceType = { Value: 4 }; //xml data
            }

            webResource.Content = Base64.encode(LicenseKey.value);
            var jsonWebResource = window.JSON.stringify(webResource);

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                url: ODataURL,
                data: jsonWebResource,
                beforeSend: function (XMLHttpRequest) {
                    //Specifying this header ensures that the results will be returned as JSON.
                    XMLHttpRequest.setRequestHeader("Accept", "application/json");
                    //If we are updating
                    if (LicenseKeyId.value) {
                        //Specify the HTTP method MERGE to update just the changes you are submitting.             
                        XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
                    }
                },
                success: function (data, textStatus, XmlHttpRequest) {
                    Message.value = "License Saved";
                    //Obtain the GUID for the web resource and save it
                    if (data.d) LicenseKeyId.value = data.d.WebResourceId;
                    //Publisdh the license web resource
                    PublishLicense();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(errorThrown);
                }
            });

        }

        //Tries to download the web resource containing the license
        function GetLicense() {

            var ODataURL = GetServerUrl() + "/XRMServices/2011/OrganizationData.svc/WebResourceSet?$filter=Name eq '" + LicensePrefix + GetGlobalContext().getOrgUniqueName() + ".lic'";

            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                url: ODataURL,
                beforeSend: function (XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("Accept", "application/json");
                },
                success: function (data, textStatus, XmlHttpRequest) {
                    //We got a response

                    if (data.d.results.length > 0) {
                        //We have a license file
                        var license = Base64.decode(data.d.results[0].Content); // get the license XML decoded from Base64
                        LicenseKey.value = license;
                        LicenseKeyId.value = data.d.results[0].WebResourceId;
                        Message.value = "License found.";
                    }
                    else {
                        //We don't have a license file
                        Message.value = "No license found.";
                    }
                },
                error: function (XmlHttpRequest, textStatus, errorObject) {                    
                    alert("OData Execution Error Occurred");
                }
            });
        }

    </script>

</head>
<body onload="GetLicense();">
    <table cellpadding="10">
        <tr>
            <td class="label">
                <h1>License Details</h1>
            </td>
        </tr>
        <tr>
            <td class="label">License Key:</td>
            <td>
                <textarea name="LicenseKey" id="LicenseKey"style="width: 100%" rows="9" cols="">Loading...</textarea>                
                <input type="hidden" name="LicenseKeyId" id="LicenseKeyId" />
            </td>
        </tr>
        <tr>
            <td class="label">
                <input type="button" value="Save" onclick="SaveLicense();" /></td>
            <td>
                <input type="text" value="" disabled="disabled" name="Message" id="Message" style="border-style: none; width: 100%; background-color: rgb(233, 237, 241);" />
            </td>
        </tr>
    </table>
</body>
</html>
